import { contextBridge, ipcRenderer } from "electron";
import { electronAPI } from "@electron-toolkit/preload";

// Custom APIs for renderer
const api = {
  // ======================================================== 窗口操作函数 ======================================================== //
  close: () => ipcRenderer.send("win-close"),
  mini: () => ipcRenderer.send("win-mini"),
  resize: (mode) => ipcRenderer.send("win-resize", mode),
  log: (info) => ipcRenderer.send("log", info),
  setAutoOpen: (flag) => ipcRenderer.send("auto-open", flag),
  // ========================================================= 软件更新 ========================================================= //
  checkUpdate: () => ipcRenderer.send("check-update"),
  toUpdate: () => ipcRenderer.send("to-update"),
  hasNewVersionListener: (callback) => {
    ipcRenderer.on("update-available", (e, info) => callback(true, info));
    ipcRenderer.on("update-not-available", (e, info) => callback(false, info));
  },
  downloadPercentListener: (callback) => {
    ipcRenderer.on("download-progress", (e, info) => callback(info));
  },
  downloadedListener: (callback) => ipcRenderer.on("update-downloaded", callback),
  updateErrListener: (callback) => ipcRenderer.on("update-error", (e, err) => callback(err)),
  updateNow: () => ipcRenderer.send("update-now"),
  // ====================================================== 数据缓存操作 ====================================================== //
  getStore: (key) => ipcRenderer.invoke("store-get", key),
  setStore: (key, value) => ipcRenderer.invoke("store-set", key, value),
  // ======================================================= http请求 ======================================================= //
  login: (username) => ipcRenderer.invoke("http-login", username),
  getWorkCenters: () => ipcRenderer.invoke("http-get-workcenters"),
  getProcessInfo: (workCenterType, templateId = undefined) =>
    ipcRenderer.invoke("http-get-process", workCenterType, templateId),
  getTechnicParams: (processId, modelCode) =>
    ipcRenderer.invoke("http-get-technic-params", processId, modelCode),
  getPartModelList: (workCenterId) => ipcRenderer.invoke("http-get-partmodels", workCenterId),
  getUserIdByCardNumber: (cardNumber) => ipcRenderer.invoke("http-card2userid", cardNumber),
  getModelShortCode: (modelCode) => ipcRenderer.invoke("http-get-short-code", modelCode),
  getPartModelMap: (modelCodes) => ipcRenderer.invoke("http-get-partmodel-map", modelCodes),
  autoPostDetection: (flag) => ipcRenderer.send("http-auto-post-detection", flag),
  delRemoteData: (uuid) => ipcRenderer.invoke("http-del-detection", uuid),
  // ===================================================== 数据库操作函数 ==================================================== //
  insertData: (data) => ipcRenderer.invoke("spc-insert", data),
  delLocalData: (uuid) => ipcRenderer.invoke("spc-del-by-uuid", uuid),
  spcGetTarget: (process, start, end, workType = undefined, finishAt = undefined) =>
    ipcRenderer.invoke("spc-get-target", process, start, end, workType, finishAt),
  finishBatch: () => ipcRenderer.invoke("finish-batch"),
  insertAnomaly: (data) => ipcRenderer.invoke("anomaly-insert", data),
  getAnomaly: (workCenterId, process, start, end) =>
    ipcRenderer.invoke("anomaly-get-target", workCenterId, process, start, end),
  // ====================================================== 串口操作函数 ==================================================== //
  getSerialPorts: () => ipcRenderer.invoke("serial-list"),
  createSerial: async (config) => {
    const port = await ipcRenderer.invoke("create-serial", config);
    return new Promise((resolve, reject) => {
      if (!port.error) {
        resolve({
          ...config,
          open: () => ipcRenderer.send(`serial-${port}-open`),
          close: () => ipcRenderer.send(`serial-${port}-close`),
          onChange: (cb) => ipcRenderer.on(`serial-${port}-status`, (_e, flag) => cb(flag)),
          onRead: (cb) => ipcRenderer.on(`serial-${port}-read`, (_e, data) => cb(data)),
          onError: (cb) => ipcRenderer.on(`serial-${port}-error`, (_e, err) => cb(err)),
          send: (d) => ipcRenderer.send(`serial-${port}-write`, d)
        });
      } else {
        reject(port.msg);
      }
    });
  }
};

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld("electron", electronAPI);
    contextBridge.exposeInMainWorld("api", api);
  } catch (error) {
    console.error(error);
  }
} else {
  window.electron = electronAPI;
  window.api = api;
}
